package com.example.springboot.utils;

import javax.servlet.http.HttpServletRequest;

//获取ip
public class IpUtils {
    public static String getIpAddr(HttpServletRequest request){
        String ip = request.getHeader("X-Forwarded-For");
        if (ip != null && ip.length() > 0 && !"unknown".equalsIgnoreCase(ip)) {
            // 如果X-Forwarded-For存在且不是unknown，则取第一个IP（可能是多个IP用逗号分隔）
            int index = ip.indexOf(',');
            if (index != -1) {
                ip = ip.substring(0, index);
            }
        } else {
            // 尝试其他头部，但通常X-Forwarded-For是首选
            ip = request.getHeader("X-Real-IP");
            if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
        }
        // 处理IPv6的本地回环地址
        return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
    }
}